#include "logger_factory.hpp"
#include "logger_builder.hpp"
#include "core/log_context.hpp"
#include <iostream>
#include <thread>
#include <vector>

// 辅助函数，用于生成随机ID，在分布式追踪示例中使用
std::string generate_random_id(size_t length) {
    static const char charset[] = "0123456789abcdef";
    std::string result;
    result.reserve(length);
    srand(time(nullptr));
    for (size_t i = 0; i < length; ++i) {
        result += charset[rand() % (sizeof(charset) - 1)];
    }
    return result;
}


// 演示如何使用 LoggerBuilder 创建一个复杂的 Logger 实例
std::shared_ptr<ILogger> create_logger_with_builder() {
    std::cout << "\n--- Creating logger with LoggerBuilder ---\n";
    
    auto builder = LoggerBuilder();

    // 使用链式调用进行配置
    auto logger = builder.withLogLevel(LogLevel::Trace) // 设置最低日志级别为 Trace
                         .withBasicFormat()             // 使用基础文本格式
                         .withConsoleSink(true)         // 添加一个控制台 Sink，并应用过滤规则
                         .withFileSink("logs/builder_app.log", 1024 * 1024, 3) // 添加文件 Sink
                         .withNetworkSink("http://127.0.0.1:8080/log") // 添加一个指向本地服务器的网络Sink
                         .withFilter("\"password\"\\s*:\\s*\"[^\"]+\"", "\"password\":\"[REDACTED]\"") // 添加过滤规则
                         .enableBacktrace(50)           // 开启最近50条日志的回溯功能
                         .build();                      // 构建 Logger 实例

    std::cout << "Logger created successfully with builder.\n";
    return logger;
}

// 演示如何从配置文件创建 Logger 实例
std::shared_ptr<ILogger> create_logger_from_config_file() {
    std::cout << "\n--- Creating logger from config/logger.json ---\n";
    try {
        auto logger = LoggerFactory::createFromConfigFile("config/logger.json");
        std::cout << "Logger created successfully from config file.\n";
        return logger;
    } catch (const std::exception& e) {
        std::cerr << "Failed to create logger from config file: " << e.what() << std::endl;
        return nullptr;
    }
}


int main() {
    // 确保日志目录存在
    std::filesystem::create_directories("logs");

    // --- 1. 使用构建器创建一个 Logger 实例 ---
    auto logger1 = create_logger_with_builder();
    if (!logger1) return 1;

    // --- 2. 使用配置文件创建另一个完全独立的 Logger 实例 ---
    auto logger2 = create_logger_from_config_file();
    if (!logger2) return 1;

    // --- 3. 演示日志记录 ---
    std::cout << "\n--- Demonstrating Logging Features ---\n";

    // 3.1 普通日志
    LOG_INSTANCE_DEBUG(logger1, "This is a debug message for logger1.");
    LOG_INSTANCE_INFO(logger2, "This is an info message for logger2 (JSON format).");

    // 3.2 使用 {fmt} 库进行格式化日志 (类型安全)
    LOG_INSTANCE_WARN(logger1, "User '{}' failed to login {} times.", "Alice", 5);
    
    // 3.3 结构化日志，附加JSON上下文
    nlohmann::json context = {
        {"user_id", 123},
        {"request_id", "abc-def-123"},
        {"password", "my_secret_password"} // 这个字段将被过滤
    };
    LOG_INSTANCE_ERROR_CTX(logger1, "Payment failed", context); // logger1 会以文本格式输出
    LOG_INSTANCE_CRITICAL_CTX(logger2, "System database connection lost", context); // logger2 会以JSON格式输出

    // 3.4 分布式追踪上下文 (Trace & Span ID)
    std::cout << "\n--- Demonstrating Trace Context ---\n";
    {
        // 使用 RAII 风格的 ContextScope，在作用域结束时自动恢复上下文
        LogContextManager::ContextScope trace_scope(generate_random_id(16), generate_random_id(8));
        LOG_INSTANCE_INFO(logger2, "Starting a new transaction...");
        // 这个作用域内的所有日志都会自动附带相同的 trace_id 和 span_id
        LOG_INSTANCE_INFO(logger2, "Processing step 1...");
        LOG_INSTANCE_WARN(logger2, "Step 2 took longer than expected.");
    }
    LOG_INSTANCE_INFO(logger2, "Transaction finished. Context has been cleared.");


    // 3.5 动态修改日志级别
    std::cout << "\n--- Demonstrating Dynamic Log Level Change ---\n";
    logger1->setLevel(LogLevel::Warn);
    LOG_INSTANCE_INFO(logger1, "This info message from logger1 should NOT be visible.");
    LOG_INSTANCE_WARN(logger1, "This warning message from logger1 IS visible.");
    logger1->setLevel(LogLevel::Trace); // 恢复
    LOG_INSTANCE_DEBUG(logger1, "This debug message from logger1 is now visible again.");

    // 3.6 触发日志回溯
    std::cout << "\n--- Demonstrating Backtrace ---\n";
    std::cout << "Dumping last 50 logs from logger1 to stderr:\n";
    logger1->dumpBacktrace();

    // --- 4. 等待异步线程处理 ---
    std::cout << "\nWaiting for async threads to flush logs...\n";
    std::this_thread::sleep_for(std::chrono::seconds(2));

    std::cout << "\nExample finished. Check logs/builder_app.log and logs/application.log\n";
    
    // main函数结束，logger1 和 logger2 的 shared_ptr 会被销毁，
    // 其管理的 Logger 对象的析构函数会被调用，自动完成所有清理工作。
    // 无需再手动调用 spdlog::shutdown()。
    return 0;
}
